#include "palette.h"
#include <tws/button.h>
#include <stdio.h>

DEFINE_RESPONSE_TABLE(PaletteWindow, Window)
  E_BUTTONUP(ID_SYSBOX, cmSysBox)
  E_MOUSEMOVE
  E_MOVEOUTSIDE
END_RESPONSE_TABLE

PaletteWindow::PaletteWindow(int x, int y) :
  Window(NULL, "Palette", x, y, x+20*16+FWIDTH*2-1, y+14*16+SysFont->height+2+CAPTION_HEIGHT+FWIDTH,
         WA_VISABLE | WA_SAVEAREA | WA_BORDER | WA_CAPTION | WA_SYSBOX)
{
  int len = StringWidth("000 R:0 G:0 B:0", SysFont);
  Paint(); // It seems this function defines the clipping region
  Colour = new StaticText(this, "", (20*16-len)/2, cy1, len);
  RefreshWindow();
}

void PaletteWindow::PaintWindow(int x1, int y1, int x2, int y2)
{
  Window::PaintWindow(x1, y1, x2, y2);
  ViewBuffer* buf = GetClientBuffer();
  int j, k, col = 0, oy = SysFont->height+2;
  for (j = 0; j < 20*16; j+=16, col++)
  {
    Box(buf, j, oy, j+15, oy+15, col);
    Box(buf, j, oy+13*16, j+15, oy+13*16+15, col+236);
  }
  for (j = oy+16; j < oy+16+12*16; j+=16)
  {
    for (k = 0; k < 18*16; k+=16)
    {
      Box(buf, k, j, k+15, j+15, col++);
    }
  }
  DeleteBuffer(buf);
}

void PaletteWindow::MouseMove(int x, int y, int, int)
{
  int col, r, g, b;
  char num[16];

  x -= absx; y -= absy;
  if (x < cx1 || y < cy1+SysFont->height+2 || x > cx2 || y > cy2) num[0] = 0;
  else
  {
    x = (x - cx1) / 16;
    y = (y - cy1-SysFont->height-2) / 16;
    if (y == 0 || y == 13)
    {
      col = (y == 0) ? x : 236+x;
      sprintf(num, "%3d R:? G:? B:?", col);
    }
    else
    {
      if (x > 17) num[0] = 0;
      else
      {
        col = (y-1)*18+x;
        r = col / 36;
        g = (col % 36) / 6;
        b = (col % 36) % 6;
        sprintf(num, "%3d R:%d G:%d B:%d", col+20, r, g, b);
      }
    }
  }
  Colour->SetText(num);
}


int main()
{
  ws.Init("mine.cfg");
  PaletteWindow Palette(110, 100);
  ws.RunEvents();
  return 0;
}
